package com.boat.starter.web.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.boat.framework.base.api.HttpConsts;
import com.boat.framework.common.thread.context.ContextUtils;
import com.boat.framework.common.thread.context.LogContext;
import com.boat.framework.common.thread.context.MockContext;

import lombok.extern.slf4j.Slf4j;

/**
 * 跟踪号过滤器
 * 
 * @author 周江
 *
 */
@Slf4j
public class TrackidFilter implements Filter {

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		try {
			// 1.获取跟踪号
			String trackId = request.getHeader(HttpConsts.RequestHeader.TRACKID);
			// 2.设置跟踪号
			LogContext.newLogContext(trackId);

			// 3.记录mock参数
			Map<String, String> headerInfo = getRequestHeaderInfo(request);
			MockContext.setHeader(headerInfo);
		} catch (Exception ex) {
			log.error("设置跟踪号出错：" + ex.getMessage(), ex);
		}

		try {
			chain.doFilter(servletRequest, servletResponse);
		} finally {
			// 清理上下文
			ContextUtils.clear();
		}
	}

	private Map<String, String> getRequestHeaderInfo(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = (String) headerNames.nextElement();
			String value = request.getHeader(key);
			map.put(key, value);
		}
		return map;
	}

}
